<?php
/******************************************************************************
*                                                                             *
* Steak Desk v0.2                                                             *
*                                                                             *
* Copyright (c) 2011 Andrew D. Zonenberg.                                     *
* All rights reserved.                                                        *
*                                                                             *
* Redistribution and use in source and binary forms, with or without modifi-  *
* cation, are permitted provided that the following conditions are met:       *
*                                                                             *
*    * Redistributions of source code must retain the above copyright notice  *
*      this list of conditions and the following disclaimer.                  *
*                                                                             *
*    * Redistributions in binary form must reproduce the above copyright      *
*      notice, this list of conditions and the following disclaimer in the    *
*      documentation and/or other materials provided with the distribution.   *
*                                                                             *
*    * Neither the name of the author nor the names of its contributors may be*
*      used to endorse or promote products derived from this software without *
*      specific prior written permission.                                     *
*                                                                             *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED *
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF        *
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN     *
* NO EVENT SHALL THE AUTHOR BE HELD LIABLE FOR ANY DIRECT, INDIRECT,          *
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT*
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, *
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF   *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING        *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS          *
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                *
*                                                                             *
*******************************************************************************/

require_once('../inc/utils.php');

/**
	@brief Program entry point
 */
function main()
{
	global $g_tplvars;
	$g_tplvars['title'] = 'List';
		
	if(!isset($_GET['action']))
	{
		header('Location: todo.php?action=summary');
		exit;
	}
	
	//Look up our access
	restricted();
	
	//legal actions
	$actions = array(
		'summary',
		'create',
		'docreate',
		'mkdep',
		'detail',
		'blocked',
		'complete',
		'completed',
		'uncomplete',
		'deleteconfirm',
		'delete',
		'unblock',
		);
		
	if(!in_array($_GET['action'], $actions))
		summary();
	else
		$_GET['action']();
}

/**
	@brief Renders a single row from the summary
	
	@param a		Database row
 */
function GetSummaryItem($a)
{
	global $g_tplvars;
	
	$g_tplvars['id'] = $a->id;
	$g_tplvars['title'] = lengthcap($a->title, 55);
	$g_tplvars['status'] = enum_value_to_name('taskstatus', $a->status);
	
	if($a->status == 0)
	{
		$g_tplvars['toggletext'] = 'done';
		$g_tplvars['toggle'] = 'complete';
	}
	else
	{
		$g_tplvars['toggletext'] = 'not done';
		$g_tplvars['toggle'] = 'uncomplete';
	}
	
	$g_tplvars['created'] =  date('H:i F d', $a->created);
	$g_tplvars['deadline'] =  date('H:i F d', $a->deadline);
	$g_tplvars['fulldesc'] = lengthcap($a->fulldesc, 100);
	if($a->blocking)
		$g_tplvars['blocking'] = $a->blocking;
	else
		$g_tplvars['blocking'] = '<span class=\'gray\'>None</span>';
	return templatize('../templates/todo-summary-item.html');
}

/**
	@brief Displays the active-tasks page
 */
function summary()
{
	$tlist = '';
	$r = dbquery('select `id`, `title`, `status`, `created`, `deadline`, `fulldesc`, '. 
				'(select count(blocked) from taskdeps where blocker = tasks.id) as blocking ' . 
				'from tasks where ' .
				'(select count(blocker) from taskdeps where blocked = tasks.id and ' . 
				'(select status from tasks as tdeps where tdeps.id = taskdeps.blocker) = 0' .
				') = 0 and ' . 
				'owner = ' . $_SESSION['uid'] . ' and ' .
				'status = 0' . 
				';');
	global $g_tplvars;
	while($a = mysql_fetch_object($r))
		$tlist .= GetSummaryItem($a);
	$g_tplvars['todolist'] = $tlist;	
	
	$g_tplvars['title'] = 'Active Tasks';
	
	render('../templates/todo-summary.html');
}

function completed()
{
	$tlist = '';
	$r = dbquery('select `id`, `title`, `status`, `created`, `deadline`, `fulldesc`, '. 
				'(select count(blocked) from taskdeps where blocker = tasks.id) as blocking ' . 
				'from tasks where ' .
				'owner = ' . $_SESSION['uid'] . ' and ' .
				'status != 0' . 
				';');
	global $g_tplvars;
	while($a = mysql_fetch_object($r))
		$tlist .= GetSummaryItem($a);
	$g_tplvars['todolist'] = $tlist;	
	
	$g_tplvars['title'] = 'Completed Tasks';
	
	render('../templates/todo-summary.html');
}

/**
	@brief Displays the blocked-tasks page
 */
function blocked()
{
	$tlist = '';
	$r = dbquery('select `id`, `title`, `status`, `created`, `deadline`, `fulldesc`, '. 
				'(select count(blocked) from taskdeps where blocker = tasks.id) as blocking ' . 
				'from tasks where ' .
				'(select count(blocker) from taskdeps where blocked = tasks.id and ' . 
				'(select status from tasks as tdeps where tdeps.id = taskdeps.blocker) = 0' .
				') != 0 and ' . 
				'owner = ' . $_SESSION['uid'] .
				';');
	global $g_tplvars;
	while($a = mysql_fetch_object($r))
		$tlist .= GetSummaryItem($a);
	$g_tplvars['todolist'] = $tlist;	
	$g_tplvars['title'] = 'Blocked Tasks';
	
	render('../templates/todo-summary.html');
}

/**
	@brief Displays the create-tasks page
 */
function create()
{
	render('../templates/todo-create.html');
}

/**
	@brief Creates a new task
 */
function docreate()
{
	//Prepare input
	$title = sanitize_db(sanitize_render($_POST['title']));
	$fulldesc = sanitize_db(sanitize_render($_POST['fulldesc']));
	$deadline = strtotime($_POST['deadline']);
	$now = time();	
	
	//Add to the database
	dbquery(
			'insert into tasks(`title`,`fulldesc`,`status`,`created`,`deadline`,`owner`) '.
			'values(\'' . $title . '\', \'' . $fulldesc . '\', \'0\', \'' . $now . '\', \'' . $deadline
			. '\', ' . $_SESSION['uid'] . ')'
		);
	
	header('Location: todo.php?action=summary');
}

/**
	@brief Creates dependency records
 */
function mkdep()
{
	//prerequisite is blocking every item in blocks
	$pre = intval($_POST['pre']);
	foreach($_POST['blocks'] as $f)
		dbquery('insert into taskdeps values(' . $pre . ', ' . intval($f) . ')');
	
	header('Location: todo.php?action=summary');
}

/**
	@brief Displays details for one task
 */
function detail()
{
	global $g_tplvars;
	
	$id = intval($_GET['id']);
	$r = dbquery('select `id`, `title`, `status`, `created`, `deadline`, `fulldesc` ' .
				'from tasks where ' .
				'owner = ' . $_SESSION['uid'] . ' and ' .
				'id = ' . $id .
				';');
	$row = mysql_fetch_object($r);
	if(mysql_num_rows($r) == 0)
	{
		render('../templates/todo-item-not-found.html');
		die;
	}
	
	//must come before we pull data out of $row
	$blockedby = '';
	$r = dbquery(
				'select tasks.id,tasks.title from taskdeps,tasks ' . 
				'where taskdeps.blocked = ' . $id . ' and tasks.id = taskdeps.blocker'
				);
	$g_tplvars['blocked'] = $id;
	while($x = mysql_fetch_object($r))
	{
		foreach($x as $a => $b)
			$g_tplvars[$a] = $b;
		$g_tplvars['blocker'] = $x->id;
		$blockedby .= templatize('../templates/todo-detail-task.html');
	}
	$g_tplvars['blockedby'] = $blockedby;
	
	$blocks = '';
	$g_tplvars['blocker'] = $id;
	$r = dbquery(
				'select tasks.id,tasks.title from taskdeps,tasks ' . 
				'where taskdeps.blocker = ' . $id . ' and tasks.id = taskdeps.blocked'
				);
	while($x = mysql_fetch_object($r))
	{
		foreach($x as $a => $b)
			$g_tplvars[$a] = $b;
		$g_tplvars['blocked'] = $x->id;
		$blocks .= templatize('../templates/todo-detail-task.html');
	}
	$g_tplvars['blocks'] = $blocks;
	
				
	foreach($row as $a => $b)
		$g_tplvars[$a] = $b;
	$g_tplvars['status'] = enum_value_to_name('taskstatus', $row->status);
	$g_tplvars['created'] = date('H:i F d', $row->created);
	$g_tplvars['deadline'] = date('H:i F d', $row->deadline);
	
	render('../templates/todo-detail.html');
}

/**
	@brief Marks a task as complete
 */
function complete()
{
	//mark the task as done
	$id = intval($_GET['id']);
	$done = enum_name_to_value('taskstatus', 'Completed');
	dbquery('update tasks set status = ' . $done . ' where id = ' . $id .
			' and owner = ' . $_SESSION['uid'] . ' limit 1');
	
	header('Location: todo.php?action=summary');
}

/**
	@brief Marks a task as incomplete
 */
function uncomplete()
{
	//mark the task as not done
	$id = intval($_GET['id']);
	$active = enum_name_to_value('taskstatus', 'Active');
	dbquery('update tasks set status = ' . $active . ' where id = ' . $id .
			' and owner = ' . $_SESSION['uid'] . ' limit 1');
	
	header('Location: todo.php?action=summary');
}

/**
	@brief Asks the user to confirm deletion of a task
 */
function deleteconfirm()
{
	global $g_tplvars;
	$g_tplvars['id'] = intval($_GET['id']);
	
	//TODO: show item info
	
	render('../templates/todo-delete-confirm.html');
}

/**
	@brief Deletes a task without prompting
 */
function delete()
{
	$id = intval($_GET['id']);
	dbquery('delete from tasks where id = ' . $id . ' and owner = ' . $_SESSION['uid'] . ' limit 1');
	
	header('Location: todo.php?action=summary');
}

function unblock()
{
	$blocker = intval($_GET['blocker']);
	$blocked = intval($_GET['blocked']);
	
	//TODO: security check, don't let us delete another user's dependencies
	
	dbquery('delete from taskdeps where `blocked` = ' . $blocked . ' and `blocker` = ' . $blocker . ' limit 1');
	
	header('Location: todo.php?action=summary');
}

/**
	@brief Trims a string with ... to keep it within a specified length constraint
 */
function lengthcap($str, $len)
{
	if(strlen($str) <= $len)
		return $str;
	return substr($str, 0, $len-3) . '...';
}
?>
